package labox.innovation.gameserver.geodata;


import org.w3c.dom.*;

public final class MapLayer {
	
	public final static int ID_MASK = 0x9FFFFFFF;

	public final static int XFLIP_MASK = 0x40000000;

	public final static int YFLIP_MASK = 0x20000000;

	private int tilew, tileh; //width and height of tile

	private int cx, cy; //多少行    多少列

	private short[] data;   

	public int width, height;

	private MapLayer() {
	}
	/****
	 * data 修改为 short [][]
	 * 2个循环为一个单元块属性
	 * data[2*j] 索引    data[2*j+1] 翻转情况
	 */
	public static MapLayer fromXML(GeoEngine pf, Element e) throws Exception {
		NodeList nl = e.getElementsByTagName("data");
		MapLayer layer = new MapLayer();
		layer.tilew = pf.getTileWidth();
		layer.tileh = pf.getTileHeight();
		layer.cx = Integer.parseInt(e.getAttribute("width"));
		layer.cy = Integer.parseInt(e.getAttribute("height"));
		layer.width = layer.tilew * layer.cx;
		layer.height = layer.tileh * layer.cy;
		layer.data = new short[layer.cx * layer.cy *2];
		if (nl.getLength() > 0) {
			e = (Element) nl.item(0);
			nl = e.getElementsByTagName("tile");
			for (int j = -1; ++j < nl.getLength();) {
				Element et = (Element) nl.item(j);		
				layer.data[2 * j]   = (short)(Integer.parseInt(et.getAttribute("gid")) - 1);	
				String s = et.getAttribute("flag");
				layer.data[2 * j + 1] = (short)Integer.parseInt(s.length() == 0 ? "0" : s);
			}
		} else {
			throw new Exception("Expect Data tag");
		}
		return layer;
	}

	public int getWidthInTile() {
		return cx;
	}

	public int getHeightInTile() {
		return cy;
	}

	public int getTileWidth() {
		return tilew;
	}

	public int getTileHeight() {
		return tileh;
	}

	public short[] getTiles() {
		return data;
	}

	public int getWidth() {
		return width;
	}

	public int getHeight() {
		return height;
	}

	public void free() {
		data = null;
	}
}
